package org.wang.generalcode.modules.sys.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.wang.generalcode.modules.sys.annotation.LogAnnotation;
import org.wang.generalcode.modules.sys.pojo.dto.CaptchaDTO;
import org.wang.generalcode.modules.sys.pojo.entity.User;
import org.wang.generalcode.modules.sys.pojo.enums.LogModuleEnum;
import org.wang.generalcode.modules.sys.service.ILoginService;
import org.wang.generalcode.modules.sys.service.IUserService;
import org.wang.generalcode.support.result.Result;



/**
 * @author wangchong
 */
@RestController
@AllArgsConstructor
@RequestMapping("/login")
@Schema(description = "登录", name = "登录接口")
public class LoginController {

    private final ILoginService loginService;

    private final IUserService userService;


    /**
     * 登录
     */
    @PostMapping("/token")
    @ApiOperationSupport(order = 1)
    @Schema(description = "登录", example = "传入username、password")
    @LogAnnotation(value = "登录", module = LogModuleEnum.LOGIN)
    public Result token(@Parameter(name = "username") @RequestParam String username,
                                @Parameter(name = "password") @RequestParam String password,
                                @Parameter(name = "captchaKey") @RequestParam String captchaKey,
                                @Parameter(name = "captchaCode") @RequestParam String captchaCode) {
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username.trim()));
        if (StrUtil.isEmptyIfStr(user)) {
            return Result.failed("用户不存在！");
        }
        if (!StrUtil.isEmptyIfStr(user.getPassword()) && !user.getPassword().equals(password)) {
            return Result.failed("密码错误！");
        }
        Result resultMap = userService.validateCaptcha(captchaKey, captchaCode);
        if (!resultMap.getCode().equals("00000")) {
            return resultMap;
        }
        StpUtil.login(user.getId());
        return Result.success(StpUtil.getTokenInfo());
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    @ApiOperationSupport(order = 1)
    @Schema(description = "登出", example = "")
    public Result token() {
        StpUtil.logout();
        return Result.success();
    }


    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    @ApiOperationSupport(order = 1)
    @Schema(description = "获取验证码", example = "")
    public Result getCaptcha() {
        CaptchaDTO captchaDTO = loginService.getCaptcha();
        return Result.success(captchaDTO);
    }

}
